/* ----------------------------------------------------------------------
*
* Copyright (C) 2025 XiaoFei. All rights reserved.
*
* @file:		XiaoFei_RTC.c
* @author:		XiaoFei
* @Date:     	14-February-2025
* @Revision: 	V1
* @Project: 	XiaoFei BSP Library
*
* -------------------------------------------------------------------- */

#include "stm32f10x.h"
#include "XiaoFei_RTC.h"
#include "time.h"

/* 
* @function: 	XiaoFei_RTCInit
* @parameter:	[in] This					 Default value of initialization process.
* @parameter:	[in] Set					 Enable or disable of the value.
*/
void XiaoFei_RTCInit(BeiJingRTC_TypeDef* This, unsigned char Set)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP,ENABLE);
	PWR_BackupAccessCmd(ENABLE);
	if(BKP_ReadBackupRegister(RTC_BKPDr)==RTC_BKPData)
	{
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
	}
	else
	{
		RCC_LSEConfig(RCC_LSE_ON);
		while(RCC_GetFlagStatus(RCC_FLAG_LSERDY)==RESET);
		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
		RCC_RTCCLKCmd(ENABLE);
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
		RTC_SetPrescaler(RTC_Freq-1);
		RTC_WaitForLastTask();
		if(Set)
		{
			static struct tm time_date;
			time_date.tm_year=This->Year-1900;
			time_date.tm_mon=This->Month-1;
			time_date.tm_mday=This->Day;
			time_date.tm_hour=This->Hour;
			time_date.tm_min=This->Minute;
			time_date.tm_sec=This->Second;
			RTC_SetCounter(mktime(&time_date)-8*60*60);
			RTC_WaitForLastTask();
		}
		BKP_WriteBackupRegister(RTC_BKPDr,RTC_BKPData);
	}
}

/* 
* @function: 	XiaoFei_RTCGetTime
* @parameter:	[out] This					 The obtained time structure.
*/
void XiaoFei_RTCGetTime(BeiJingRTC_TypeDef* This)
{
	static struct tm time_date;
	static time_t time_cnt;
	time_cnt=RTC_GetCounter()+8*60*60;
	time_date=*localtime(&time_cnt);
	This->Year=time_date.tm_year+1900;
	This->Month=time_date.tm_mon+1;
	This->Day=time_date.tm_mday;
	This->Hour=time_date.tm_hour;
	This->Minute=time_date.tm_min;
	This->Second=time_date.tm_sec;
	This->Milliscond=(RTC_Freq-RTC_GetDivider())/(float)RTC_Freq*999.0;
}



